package cn.topevery.garden.dal.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.topevery.garden.dal.constant.StringConstant;
import cn.topevery.garden.dal.dao.ProjBidDao;
import cn.topevery.garden.entity.dto.ProjBidCudDTO;
import cn.topevery.garden.entity.dto.ProjBidDTO;
import cn.topevery.garden.entity.po.ProjBasicInfo;
import cn.topevery.garden.entity.po.ProjBid;
import cn.topevery.garden.entity.po.ProjFiles;
import cn.topevery.garden.entity.query.ProjBidQuery;
import cn.topevery.garden.entity.vo.ProjBidAndFilesVO;
import cn.topevery.garden.entity.vo.ProjBidAndProjNameVO;

import cn.topevery.garden.entity.vo.ProjFilesVO;
import cn.topevery.garden.framework.base.BaseLogic;
import cn.topevery.garden.framework.Database;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.base.BaseEntityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 项目招标表
 *
 * @author code-generate
 * @date 2022-11-02
 */
@Service
public class ProjBidLogic extends BaseLogic<ProjBid> {
    @Autowired
    ProjBidDao projBidDao;
    @Autowired
    ProjBasicInfoLogic projBasicInfoLogic;
    @Autowired
    ProjFilesLogic projFilesLogic;

    @Override
    public BaseEntityDao<ProjBid, Integer> getDao() {
        return projBidDao;
    }

    

    /**
     * 获取列表
     *
     * @param query
     */
    public DataPager<ProjBidAndProjNameVO> listPage(ProjBidQuery query) {
        return projBidDao.listPage(query);
    }

    public List<ProjBidAndProjNameVO> list(ProjBidQuery query) {
        List<ProjBidAndProjNameVO> projBidVoList = projBidDao.list(query);
        // 当传入的项目ID不为空时，查询标段附件信息
        if (ObjectUtil.isNotEmpty(query.getProjId())) {
            if (CollUtil.isNotEmpty(projBidVoList)) {
                // 获取项目及招标文件
                List<ProjFilesVO> filesList = projFilesLogic.listByProjIdAndStageTypeCode(query.getProjId(), StringConstant.ProjStageFileCode.ProjBid);
                if (CollUtil.isNotEmpty(filesList)) {
                    for (ProjBidAndProjNameVO projBidVo : projBidVoList) {
                        List<ProjFilesVO> projBidFilesVOs = filesList.stream().filter(files -> ObjectUtil.isNotEmpty(files.getProjStageId()) && files.getProjStageId().equals(projBidVo.getProjBidId())).collect(Collectors.toList());
                        projBidVo.setFiles(projBidFilesVOs);
                    }
                }
            }
        }
        return projBidVoList;
    }

    /**
     * 根据自增id批量删除
     *
     * @param ids
     */
    public void deleteBatchById(String userId,Integer[] ids) {
      Database.transactionScope(() -> {
            // 根据ID查询招标信息
            ProjBidQuery query = new ProjBidQuery();
            query.setIds(ids);
            List<ProjBidAndProjNameVO> bidList = this.projBidDao.list(query);
            if (CollUtil.isEmpty(bidList)) {
                return;
            }
            List<String> bidIds = bidList.stream().map(bidVO -> bidVO.getProjBidId()).collect(Collectors.toList());


            projBidDao.delete(userId, ids);

            // 删除对应附件
            projFilesLogic.updateFilesByProjStageIds(bidIds, null, userId);
        });
    }

    public boolean saveOrUpdateOrDelete(String userId, ProjBidCudDTO cudDto) {
        if (ObjectUtil.isEmpty(cudDto)) {
            throw new RuntimeException("传入的集合不能为空！");
        }
        Database.transactionScope(() -> {
            List<ProjBidDTO> dtoList = cudDto.getSaveAndUpdateProjBidList();
            if (CollUtil.isNotEmpty(dtoList)) {
                this.saveOrUpdate(userId, dtoList);
            }
            Integer[] deleteIds = cudDto.getDeleteIds();
            if (ObjectUtil.isNotEmpty(deleteIds)) {
                this.deleteBatchById(userId, deleteIds);
            }
        });
        return true;
    }

    public boolean saveOrUpdate(String userId, List<ProjBidDTO> dtoList) {
        if (CollUtil.isEmpty(dtoList)) {
            throw new RuntimeException("传入的集合不能为空！");
        }
        // 校验标段数据
        for (ProjBidDTO dto : dtoList) {
            this.checkProjBidData(dto);
        }
        Database.transactionScope(() -> {
            // 新增 修改
            for (ProjBidDTO dto : dtoList) {
                ProjBid projBid = new ProjBid();
                BeanUtil.copyProperties(dto, projBid);

                // 保存数据
                this.projBidDao.saveOrUpdate(userId, projBid);

                //  保存附件
                if (ObjectUtil.isNotEmpty(dto.getFiles())) {
                    List<ProjFiles> files = dto.getFiles().stream().filter(i -> ObjectUtil.isEmpty(i.getId())).collect(Collectors.toList());
                    files.stream().forEach(i -> {
                        i.setProjId(dto.getProjId());
                        i.setProjStageId(projBid.getProjBidId());
                    });
                    if (CollUtil.isNotEmpty(files)) {
                        projFilesLogic.insert(userId, files);
                    }
                }
                //  删除附件
                if (ObjectUtil.isNotEmpty(dto.getDeleteFileIds())) {
                    projFilesLogic.delete(userId, dto.getDeleteFileIds());
                }
            }


        });
        return true;
    }

    private void checkProjBidData(ProjBidDTO dto) {
        if (ObjectUtil.isEmpty(dto)) {
            throw new RuntimeException("传入的对象不能为空！");
        }
        if (ObjectUtil.isEmpty(dto.getProjId())) {
            throw new RuntimeException("项目ID不能为空！");
        }
        // 当不为空时为修改
        if (ObjectUtil.isNotEmpty(dto.getProjBidId())) {
            // 根据项目招标ID查询信息的有效性
            ProjBid projBid = this.getEntityById(dto.getProjBidId());
            if (ObjectUtil.isEmpty(projBid)) {
                throw new RuntimeException("该招标信息在系统不存在，请检查或刷新数据！");
            }
            dto.setId(projBid.getId());
        } else {
            dto.setProjBidId(UUID.randomUUID().toString());
        }

        // 校验附件
        this.projFilesLogic.checkFilesAndSetStageId(dto.getFiles(), dto.getProjBidId());

        // 检查项目ID
        ProjBasicInfo projBasicInfo = projBasicInfoLogic.getByProjId(dto.getProjId());
        if (ObjectUtil.isEmpty(projBasicInfo)) {
            throw new RuntimeException("该项目不存在，请检查!");
        }
    }



    public ProjBid getEntityById(String projBidId) {
        if (ObjectUtil.isEmpty(projBidId)) {
            throw new RuntimeException("传入的标段ID不能为空");
        }
        return this.projBidDao.getEntityByGuidId(projBidId);
    }

    public ProjBidAndFilesVO getBidAndFilesById(String guidId) {
        if (ObjectUtil.isEmpty(guidId)) {
            throw new RuntimeException("传入的标段ID不能为空");
        }
        ProjBidAndFilesVO projBidAndFilesVO = new ProjBidAndFilesVO();
        ProjBid projBid = this.projBidDao.getEntityByGuidId(guidId);
        if (ObjectUtil.isEmpty(projBid)) {
            return projBidAndFilesVO;
        }
        BeanUtil.copyProperties(projBid, projBidAndFilesVO);

        // 查询项目信息
        if (ObjectUtil.isNotEmpty(projBid) && ObjectUtil.isNotEmpty(projBid.getProjId())) {
            ProjBasicInfo projBasicInfo = this.projBasicInfoLogic.getByProjId(projBid.getProjId());
            projBidAndFilesVO.setProjBasicInfo(projBasicInfo);
        }

        // 查询附件信息
        List<ProjFilesVO> baseInfoFiles = projFilesLogic.listByProjIdAndStageId(projBid.getProjId(), projBid.getProjBidId());
        projBidAndFilesVO.setFiles(baseInfoFiles);

        return projBidAndFilesVO;
    }
}
